(function($){


    function apiRequest(option){

        var defaultOption={
            baseURL:"",
            code:{
                SUCCESS: "SUCCESS"
                ,ERROR: "ERROR"
                ,EXCEPTION: "EXCEPTION"
            },
            request:function(config){

            },
            response:function(XHR,resolve,reject,that){

            }
        };

        this.layerIndex=[];

        $.extend(defaultOption,option);

        this.options=defaultOption;


        this.handler={
            error:function (result) {
                var msg;
                var state=result.readyState;
                if(!!result.responseJSON){
                    msg=result.responseJSON.message;

                }else if(state==0){
                    msg='请求路径不存在';
                }else{
                    msg='服务异常';
                }
                $.QuickAlert.alertFail({content: msg});
            },
            exceptionback:function(result){
                $.QuickAlert.alertFail({
                    content: result['message']
                });
            }
        };


    };
    apiRequest.prototype._baseRequest=function(target,options){
        var that=this;
        //console.log(that);

        return new Promise(function(resolve,reject){
            var url = that.options.baseURL+target;
            //console.log('url',url);
            that.resolve=resolve;
            that.reject=reject;

            var defaultOption={
                url:url,
                //发送请求前的拦截
                beforeSend:function(XHR){
                    that.options.request(XHR);
                    that.layerIndex.push(
                        layer.open({
                            type:2
                        })
                    );
                },
                //请求完成调用 用于响应拦截
                complete:function(XHR,TS){

                    //layer.close(that.layerIndex);

                    //关闭加载框
                    if(that.layerIndex.length>1){
                        that.layerIndex.shift();
                    }else{
                        layer.close(that.layerIndex[0]);
                    }

                    if(XHR.readyState === 4&&XHR.status===200){
                        that.XHR=XHR;
                        that.options.response(XHR,resolve,reject,that);
                    }else{
                        that.handler.error(XHR);
                        try {
                            ///throw new commonException("111",'0');
                            throw  new Error('ajax请求失败');
                        }
                        catch (e) {
                            reject(e);
                        }
                    }
                }
            };
            $.extend(defaultOption,options);
            $.ajax(
                defaultOption
            );
        });
    };


    $.api=function(pageApi){

        var apiInit=new apiRequest({
            baseURL:'/api/',
            request:function(config){

            },
            response:function(XHR,resolve,reject,that){
                var tool={
                    XHR:XHR,
                    resolve:resolve,
                    reject:reject
                };

                var response=tool.XHR;
                var result=response.responseJSON;

                try{
                    var code = result.code!=undefined?result.code:"";

                    if(code === that.options.code.SUCCESS){
                        tool.resolve(result);
                    }else if(code.indexOf(that.options.code.ERROR) == 0){
                        that.handler.error(response);
                        try {
                            throw new Error('服务内部错误','0');
                        }
                        catch (e) {
                            tool.reject(e);
                        }

                    }else if(code.indexOf(that.options.code.EXCEPTION) == 0){
                        that.handler.error(response);
                        try {
                            throw new Error('业务错误','0');
                        }
                        catch (e) {
                            tool.reject(e);
                        }
                    }else{
                        tool.resolve(result);
                    }
                }catch (err){
                    //console.log(err);
                    tool.reject(err);

                }
            },
        });

        var createPageApi=function (apiData){
            var page={};
            $.each(apiData,function(key,data){
                if(data.url){
                    page[key]=function(option){
                        var options=typeof option =='object'?option:{};
                        if(data.type){
                            options.type=data.type;
                        }
                        return apiInit._baseRequest(data.url,options);
                    };
                }else{
                    page[key]=createPageApi(data);
                }
            });
            return page;
        };

        var api=createPageApi(pageApi);

        return api;
    };


})(jQuery);




/*
//调用
$.api.login().then(function(data){
    //成功回调
}).catch(function(error){
    //错误回调
});


//调用异步嵌套
$.api.login().then(function(data){
    return $.api.getUserInfoGzd();
}).then(function(data){

});*/
